# -*- coding: utf8 -*-
import os
import jinja2
import webapp2
import json

from game_template import *
from game_history import *

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])


class OneResult():
    def __init__(self, partner='', explained=0):
        self.partner = partner
        self.explained = explained
        self.accounted = False

    def add_explained(self):
        self.explained += 1

    def set_accounted(self):
        self.accounted = True

    def is_free(self):
        return not(self.accounted)


class PairResult():
    def __init__(self, player_1='', player_2='',
                 first_explained=0, first_guessed=0):
        self.player_1 = player_1
        self.player_2 = player_2
        self.first_explained = first_explained
        self.first_guessed = first_guessed
        self.sum = 0

    def count_sum(self):
        self.sum = self.first_explained + self.first_guessed

def gen_pair_results(game):
        gresult = dict()
        for result in game.guess_results:
            player1 = game.players[game.rounds[result.round_].player_explain]
            player2 = game.players[game.rounds[result.round_].player_guess]
            gresult[player1] = OneResult(partner=player2)
        for result in game.guess_results:
            player1 = game.players[game.rounds[result.round_].player_explain]
            player2 = game.players[game.rounds[result.round_].player_guess]
            if result.result == WordGuessResult.GUESS:
                gresult[player1].add_explained()
        pair_results = []
        for result in gresult:
            cur_partner = gresult[result].partner
            if not(cur_partner) in gresult or gresult[cur_partner].is_free():
                if cur_partner in gresult:
                    second_explained = gresult[gresult[result].
                                               partner].explained
                else:
                    second_explained = 0
                a = PairResult(player_1=result,
                               player_2=gresult[result].partner,
                               first_explained=gresult[result].explained,
                               first_guessed=second_explained)
                a.count_sum()
                gresult[result].set_accounted()
                pair_results.append(a)

        pair_results = sorted(pair_results, key=lambda x: x.sum, reverse=True)
        return pair_results

class CreateGameResults(webapp2.RequestHandler):
    def get(self):
        game_id = int(self.request.get("game_id"))
        game = GameHistory.get_by_id(game_id)
        pair_results = gen_pair_results(game)
        unused_words = game.unused_words
        if len(unused_words) == 0:
            unused_words.append(u'Все слова использованы')
        template = JINJA_ENVIRONMENT.get_template('game_results.html')
        self.response.write(
            template.render(
                {"unused_words": unused_words[:-1],
                 "last_unused_word": unused_words[-1],
                 "pairs": pair_results}))


class CreateManyGamesResults(webapp2.RequestHandler):
    def get(self):
        game_ids = self.request.get("game_ids")
        unused_words = None
        pair_results = []
        for game_id_str in game_ids.split(","):
            game_id = int(game_id_str.strip())
            game = GameHistory.get_by_id(game_id)
            pair_results += gen_pair_results(game)
            if unused_words is None:
                unused_words = set(game.unused_words)
            else:
                unused_words &= set(game.unused_words)
        if len(unused_words) == 0:
            unused_words.add(u'Все слова использованы')
        template = JINJA_ENVIRONMENT.get_template('game_results.html')
        unused_words = list(unused_words)
        pair_results = sorted(pair_results, key=lambda x: x.sum, reverse=True)
        self.response.write(
            template.render(
                {"unused_words": unused_words[:-1],
                 "last_unused_word": unused_words[-1],
                 "pairs": pair_results}))
